<template>
  <div class="com-container">
    <div class="con-chart" ref="hot_ref">哈哈</div>
    <!-- 左右箭头 -->
    <span class="iconfont arr-left" @click="toLeft" :style="fontSizeSystem"
      >&#xe6ef;</span
    >
    <span class="iconfont arr-right" @click="toRight" :style="fontSizeSystem"
      >&#xe6ed;</span
    >
    <span class="cat-name" :style="fontSizeSystem">{{ catName }}</span>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { getThemeValue } from "../utils/theme_utils";

export default {
  data() {
    return {
      chartInstance: null,
      allData: null,
      currentIndex: 0, //当前所展示的一级分类数据
      titleFontSize: 0,
    };
  },
  created() {
    // console.log(this.$nextTick);
    //在组件创建完成后，进行回调函数的注册
    this.$socket.registerCallBack("hotData", this.getData);
  },
  mounted() {
    this.initChart();
    // this.getData();
    //发送数据给服务器,获取数据
    this.$socket.send({
      action: "getData",
      socketType: "hotData",
      chartName: "hotproduct",
      value: "",
    });
    window.addEventListener("resize", this.screenAdapter);
    //在页面加载完成时,主动进行屏幕的适配
    this.screenAdapter();
  },
  destroyed() {
    //组件销毁时,取消监听器
    window.removeEventListener("resize", this.screenAdapter);
    //在组件销毁后，进行回调函数的移除
    this.$socket.removeCallBack("hotData");
  },
  watch: {
    theme() {
      this.chartInstance.dispose(); //销毁当前图表
      this.initChart(); //重新初始化新主题的图表
      this.updateChart(); //更新图表
      this.screenAdapter(); //完成图表的适配
    },
  },
  computed: {
    ...mapState(["theme"]),
    catName() {
      if (!this.allData) {
        return "";
      }
      return this.allData[this.currentIndex].name;
    },
    fontSizeSystem() {
      return {
        fontSize: this.titleFontSize + "px",
        color: getThemeValue(this.theme).titleColor,
      };
    },
  },
  methods: {
    initChart() {
      this.chartInstance = this.$echarts.init(this.$refs.hot_ref, this.theme);
      const initOption = {
        title: {
          text: " | 热销商品的占比",
          left: 20,
          top: 20,
        },
        legend: {
          top: "15%",
          left: "7%",
          icon: "circle",
        },
        //工具栏
        tooltip: {
          show: true,
          backgroundColor: "rgba(0,0,0,0.5)",
          borderColor: "gray", //设置边框颜色
          textStyle: {
            color: "white", //设置文字颜色
          },
          formatter: (arg) => {
            // console.log(arg);
            const thirdCategory = arg.data.children;
            //计算三级分类的数值总和
            let total = thirdCategory.reduce((pre, item) => {
              return (pre += item.value);
            }, 0);
            let retStr = "";
            thirdCategory.map((item) => {
              retStr += `
                    ${item.name}:${
                parseInt((item.value / total) * 100) + "%"
              } <br/>
                `;
            });
            return retStr;
          },
        },
        series: [
          {
            type: "pie",
            label: {
              show: false,
            },
            emphasis: {
              labelLine: {
                show: false,
              },
            },
          },
        ],
      };
      this.chartInstance.setOption(initOption);
    },
    //获取数据
    async getData(ret) {
      //获取服务器的数据,对this.allData进行赋值后,调用updateChart更新图表
      // const { data: ret } = await this.$http.get("/hotproduct");
      this.allData = ret;
      this.updateChart();
    },
    updateChart() {
      const legendData = this.allData[this.currentIndex].children.map(
        (item) => {
          return item.name;
        }
      );
      const seriesData = this.allData[this.currentIndex].children.map(
        (item) => {
          return {
            name: item.name,
            value: item.value,
            children: item.children,
          };
        }
      );
      const dataOption = {
        legend: {
          data: legendData,
        },
        series: [
          {
            data: seriesData,
          },
        ],
      };
      this.chartInstance.setOption(dataOption);
    },
    //当浏览器的大小发生变化时,调用该函数,完成屏幕适配
    screenAdapter() {
      //获取文字的大小
      this.titleFontSize = (this.$refs.hot_ref.offsetWidth / 100) * 3.2;
      const adapterOption = {
        title: {
          textStyle: {
            fontSize: this.titleFontSize,
          },
        },
        legend: {
          itemWidth: this.titleFontSize / 2,
          itemHeight: this.titleFontSize / 2,
          itemGap: this.titleFontSize / 2,
          textStyle: {
            fontSize: this.titleFontSize / 2,
          },
        },
        series: [
          {
            radius: this.titleFontSize * 5,
            center: ["50%", "54%"],
          },
        ],
      };
      this.chartInstance.setOption(adapterOption);
      this.chartInstance.resize();
    },
    //点击左箭头的回调
    toLeft() {
      console.log(this.currentIndex);
      this.currentIndex--;
      if (this.currentIndex < 0) {
        this.currentIndex = this.allData.length - 1;
      }
      this.updateChart();
    },
    toRight() {
      this.currentIndex++;
      if (this.currentIndex > this.allData.length - 1) {
        this.currentIndex = 0;
      }
      this.updateChart();
    },
  },
};
</script>

<style lang="less" scoped>
.arr-left {
  position: absolute;
  left: 10%;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  color: #fff;
}
.arr-right {
  position: absolute;
  right: 10%;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  color: #fff;
}
.cat-name {
  position: absolute;
  left: 80%;
  bottom: 40px;
  color: #fff;
}
</style>